package io.gitee.yxsnake.tenant.datasource.init;

import io.gitee.yxsnake.tenant.datasource.CustomDynamicDataSource;
import io.gitee.yxsnake.tenant.datasource.context.DataSourceContextHolder;
import io.gitee.yxsnake.tenant.datasource.model.dto.TenantDatasourceDTO;
import io.gitee.yxsnake.tenant.datasource.model.entity.Datasource;
import io.gitee.yxsnake.embark.web.core.assertion.Assert;
import io.gitee.yxsnake.embark.web.core.utils.JsonUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.hutool.core.text.StrUtil;
import org.dromara.hutool.http.HttpUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @author: snake
 * @create-time: 2024-10-10
 * @description: 数据源初始化
 * @version: 1.0
 */
@Slf4j
@Component
@RequiredArgsConstructor
@Order(Ordered.HIGHEST_PRECEDENCE)
public class DynamicDatasourceInit implements ApplicationRunner {

    @Value("${datasource.config.url:}")
    private String datasourceConfigUrl;

    private final CustomDynamicDataSource dynamicDataSource;
    @Override
    public void run(ApplicationArguments args) {
        //租户端不进行服务调用
        log.info("==服务启动后，初始化数据源==");
        //切换默认数据源 即tenant库的数据源，用于查询tenant表中的所有tenant数据库配置
        DataSourceContextHolder.setDBType("default");
        //设置所有数据源信息
        log.info("获取当前数据源：" + DataSourceContextHolder.getDBType());
        List<Datasource> tenantInfoList = getDatasourceList();
        for (Datasource info : tenantInfoList) {
            TenantDatasourceDTO tenantDatasourceDTO = new TenantDatasourceDTO();
            BeanUtils.copyProperties(info, tenantDatasourceDTO);
            dynamicDataSource.addDataSource(tenantDatasourceDTO);
        }
        log.info("动态数据源对象中的所有数据源, 已加载数据源个数: {}", dynamicDataSource.backupTargetDataSources.size());
        log.info("初始化多租户数据库配置完成...");
    }

    private List<Datasource> getDatasourceList(){
        String result = HttpUtil.get(datasourceConfigUrl, 5000);
        Assert.isFalse("读取数据源配置信息为空",StrUtil.isBlank(result));
        List<Datasource> list = JsonUtils.parseArray(result, Datasource.class);
        return list;
    }
}
